import React, { useEffect, useState ,useRef} from 'react'
import { Steps,Button,Form, Input,Select,PageHeader,notification} from 'antd';
import { useNavigate} from 'react-router-dom';
import style from './index.module.css'
import axios from 'axios'
import { NewsEditor } from '../../../components/newsmanage/NewsEditor';
import { message } from 'antd';

export default function NewsAdd(props) {
  const navigate=useNavigate()
  // console.log("props:",props);
  const [current,setCurrent]=useState(0)
  const [sub,setSub]=useState([])
  const [classification,setClassification]=useState('时事新闻')
  const NewsForm=useRef(null)
  const [formInfo,setformInfo]=useState({})
  const [content,setContent]=useState("")
  const [,setAuditState]=useState('')
  const User=JSON.parse(localStorage.getItem('token'))
  // console.log("User:",User);
  const onFinish = (values: any) => {
    console.log('Success:', values);
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  const handleNext=()=>{
    if(current===0){
      NewsForm.current.validateFields().then(res=>{
        // console.log(res);
        setformInfo(res)
      setCurrent(current+1)
      }).catch(error=>{
        console.log(error);
      })
    }else{
      if(content===""||content.trim()==="<p></p>"){
          message.error("新闻内容不能为空")
      }else{
        setCurrent(current+1)
      }
      // console.log(formInfo,content);
     
    }
  
  }
  const handlePrevious=()=>{
    setCurrent(current-1)
  }
  useEffect(()=>{
   axios.get('http://localhost:8000/categories').then(res=>{
    // console.log(res);
    setSub(res.data)
    })
    
  },[])

  const handleSave=(auditState)=>{
    axios.post('http://localhost:8000/news',{
     ...formInfo,
      "content":content,
      "region": User.region?User.region:"全球",
      "author": User.username,
      "roleId": User.roleId,
      "auditState": auditState,//0草稿箱，1待审核，2审核通过，3审核被拒绝
      "publishState": 0,//未发布
      "createTime": Date.now(),
      "star": 0,
      "view": 0,
      //  "id": 1,
      // "publishTime": 0
    }).then(res=>{
      navigate(auditState===0?'/news-manage/draft':'/audit-manage/list');
      // props.history.push(auditState===0?'/news-manage/draft':'/audit-manage/list');
      notification.info({
        message: `通知`,
        description:
          `您可以到${auditState===0?'草稿箱':'审核列表'}中查看您的新闻`,
        placement:'bottomRight',
      });
    })
    setAuditState(auditState)
  }
  const onSelect=(item)=>{
      setClassification(item)
  }
  console.log("Classification",classification);
  return (
    <div className='container'>
    <PageHeader
    title="撰写新闻"
    // subTitle="This is a subtitle"
  />

      <Steps
        current={current}
        style={{fontWeight:'bold'}}
        items={[
          {
            title: '基本信息',
            description:'新闻标题，新闻分类',
          },
          {
            title: '新闻内容',
            description:'新闻主体内容',
          },
          {
            title: '新闻提交',
            description:"保存草稿或提交审核",
          },
        ]}
        />
       <div style={{marginTop:'50px'}}>
       <div className={current===0?'':style.active}>
      <Form
      ref={NewsForm}
      name="basic"
      initialValues={{ remember: true }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item
        label="新闻标题"
        name="title"
        rules={[{ required: true, message: 'Please input your username!' }]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="新闻分类"
        name="categoryId"
        rules={[{ required: true, message: 'Please input your password!' }]}
      >
      <Select
      defaultValue={classification}
      allowClear
      options={sub}
      onSelect={onSelect}
    />
      </Form.Item>
     

      {/* <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
        <Button type="primary" htmlType="submit">
         下一步
        </Button>
      </Form.Item> */}
        </Form>
        </div>
        <div className={current===1?'':style.active}>
          <NewsEditor getContent={(value)=>{
            // console.log(value)
            setContent(value)
            }}></NewsEditor>
        </div>
        <div className={current===2?'':style.active}></div>
       </div>
        <div style={{marginTop:'50px'}}>
         {current===2&&
          <span>
            <Button type="primary" onClick={()=>handleSave(0)}>保存草稿</Button>
            <Button danger onClick={()=>handleSave(1)}>提交审核</Button>
          </span>}
         {current<2&&<Button type="primary" onClick={handleNext}>下一步</Button>}
         {current>0&&<Button onClick={handlePrevious}>上一步</Button>}
        </div>
    </div>
  )
}
      